// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/* Copyright (c) 2020 Facebook */
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include "kprobe_test.h"

char LICENSE[] SEC("license") = "Dual BSD/GPL";

struct {
	__uint(type, BPF_MAP_TYPE_RINGBUF);
	__uint(max_entries, 256 * 1024);
} cb_events SEC(".maps");

const volatile unsigned long long min_duration_ns = 0;

SEC("kprobe/sock_alloc_file")
int BPF_KPROBE(sock_alloc_file, struct socket* sock, int flags, const char* dname) {
	struct kprobe_test_event* e;
	pid_t pid;
	int ppid;
	struct task_struct* task;
	int cpu_id;

	pid = bpf_get_current_pid_tgid() >> 32;
	task = (struct task_struct*)bpf_get_current_task();
	ppid = BPF_CORE_READ(task, real_parent, tgid);
	cpu_id = bpf_get_smp_processor_id();

	bpf_printk("sock_alloc_file: pid=%d, ppid=%d, cpu_id=%d\n", pid, ppid, cpu_id);
	/* reserve sample from BPF ringbuf */
	e = bpf_ringbuf_reserve(&cb_events, sizeof(*e), 0);
	if (!e) {
		return 1;
	}

	e->pid = pid;
	e->ppid = ppid;
	e->cpu_id = cpu_id;
	e->kstack_sz = bpf_get_stack(ctx, &e->kstack, sizeof(e->kstack), 0);
	// e->ustack_sz = bpf_get_task_stack(task, &e->ustack, sizeof(e->ustack), 0);
	e->ustack_sz = bpf_get_stack(ctx, &e->ustack, sizeof(e->ustack), BPF_F_USER_STACK);
	if (bpf_get_current_comm(e->comm, sizeof(e->comm)))
		e->comm[0] = 0;

	/* successfully submit it to user-space for post-processing */
	bpf_ringbuf_submit(e, 0);
	return 0;
}
